<template>
  <div class="profile-settings">
    <h1>个人设置</h1>
    <div class="profile-form">
      <div class="avatar-section">
        <img :src="user.avatar || '/default-avatar.png'" alt="用户头像">
        <input type="file" @change="handleAvatarUpload" accept="image/*">
      </div>

      <form @submit.prevent="updateProfile">
        <div class="form-group">
          <label>姓名</label>
          <input v-model="profileForm.name" required>
        </div>

        <div class="form-group">
          <label>邮箱</label>
          <input v-model="profileForm.email" type="email" required>
        </div>

        <div class="form-group">
          <label>个人简介</label>
          <textarea v-model="profileForm.bio"></textarea>
        </div>

        <div class="password-section">
          <h3>修改密码</h3>
          <div class="form-group">
            <label>当前密码</label>
            <input v-model="passwordForm.currentPassword" type="password">
          </div>
          <div class="form-group">
            <label>新密码</label>
            <input v-model="passwordForm.newPassword" type="password">
          </div>
          <div class="form-group">
            <label>确认新密码</label>
            <input v-model="passwordForm.confirmPassword" type="password">
          </div>
        </div>

        <button type="submit">保存更改</button>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth.store'

const authStore = useAuthStore()
const user = ref(null)

const profileForm = ref({
  name: '',
  email: '',
  bio: ''
})

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

onMounted(async () => {
  user.value = await authStore.getCurrentUser()
  profileForm.value = { ...user.value }
})

const handleAvatarUpload = async (event) => {
  const file = event.target.files[0]
  await authStore.updateAvatar(file)
}

const updateProfile = async () => {
  await authStore.updateProfile(profileForm.value)
  
  if (passwordForm.value.newPassword) {
    await authStore.updatePassword(passwordForm.value)
  }
}
</script>

<style scoped>
.profile-settings {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-section img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.password-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
